//
//  RegisterViewController.m
//  MyLittleBrother
//
//  Created by speeda on 17/7/29.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *mobileTextField;
@property (weak, nonatomic) IBOutlet UITextField *testTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *agreementButton;

@property (weak, nonatomic) IBOutlet UIButton *testButton;

/** 保存倒计时的时长 */
@property (nonatomic, assign) NSInteger tempDurationOfCountDown;
/** 定时器对象 */
@property (nonatomic, strong) NSTimer *countDownTimer;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginButtonBottom;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)keyboardChangeFrame:(NSNotification*)noti {
    
    CGRect rect= [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat keyboardheight = rect.size.height;
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat curve = [noti.userInfo[UIKeyboardAnimationCurveUserInfoKey]doubleValue];
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        self.loginButtonBottom.constant = keyboardheight + 20;
        [self.view layoutIfNeeded];
    }];
    
}


-(void)keyboardHide:(NSNotification *)noti {
    
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat curve = [noti.userInfo[UIKeyboardAnimationCurveUserInfoKey]doubleValue];
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        self.loginButtonBottom.constant = 20;
        [self.view layoutIfNeeded];
    }];
}


#pragma mark -- 发送验证码
- (IBAction)testBtnAction:(id)sender {

    [self requestGetcode];
}



#pragma mark -- 协议
- (IBAction)agreementBtnAction:(id)sender {
    
    
}


#pragma mark -- 注册
- (IBAction)registerBtnAction:(id)sender {
    
    [self requestReg];
}

#pragma mark -- 获取验证码
- (void)requestGetcode {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"getcode";
    dict[@"mobile"] = self.mobileTextField.text;
    dict[@"modeltype"] = @"reg";
    dict[@"smsfrom"] = @"ios";
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            NSLog(@"获取验证码 = %@",responseObject);
            [SVProgressHUD showSuccessWithStatus:@"验证码发送成功"];
            [self startCountDown];
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


- (void)requestReg {

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"reg";
    dict[@"mobile"] = self.mobileTextField.text;
    dict[@"password"] = self.passwordTextField.text;
    dict[@"authcode"] = self.testTextField.text;
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
        
            [self.navigationController popViewControllerAnimated:YES];
            
        } else {
        
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];

}

#pragma mark - 验证码倒计时
- (void)startCountDown {
    
    [_testButton setTitle:@"59s后重试" forState:UIControlStateNormal];
    _testButton.userInteractionEnabled = NO;
    // 设置默认的倒计时时长为60秒
    self.tempDurationOfCountDown = 60;
    // 创建定时器
    self.countDownTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateIDCountDownButtonTitle) userInfo:nil repeats:YES];
    // 将定时器添加到当前的RunLoop中（自动开启定时器）
    [[NSRunLoop currentRunLoop] addTimer:self.countDownTimer forMode:NSRunLoopCommonModes];
}

- (void)updateIDCountDownButtonTitle {
    if (self.tempDurationOfCountDown == 0) {
        // 设置IDCountDownButton的title为开始倒计时前的title
        _testButton.userInteractionEnabled = YES;
        [_testButton setTitle:@"发送验证码" forState:UIControlStateNormal];
        [self.countDownTimer invalidate];
    } else {
        // 设置IDCountDownButton的title为当前倒计时剩余的时间
        _testButton.userInteractionEnabled = NO;
        [_testButton setTitle:[NSString stringWithFormat:@"%zds后重试", self.tempDurationOfCountDown--] forState:UIControlStateNormal];
        
    }
}


@end
